//
//  NSObject+extension.swift
//  cabbage_swift
//
//  Created by dfsx6 on 2021/9/16.
//

import Foundation
import UIKit

//MARK:-
extension NSObject {
    /// 最顶部控制器
    public var exTopVC: UIViewController? {
        guard let rootViewController = UIApplication.shared.windows.first?.rootViewController else { return nil }
        return topVC(for: rootViewController)
    }
    
    ///
    fileprivate func topVC(for rootViewController: UIViewController) -> UIViewController? {
        
        if let tabbarController = rootViewController as? UITabBarController {
            guard let selectedViewController = tabbarController.selectedViewController else { return nil }
            return topVC(for: selectedViewController)
        }
        else if let navigationController = rootViewController as? UINavigationController {
            guard let visibleViewController = navigationController.visibleViewController else { return nil }
            return topVC(for: visibleViewController)
        }
        else if let presentedController = rootViewController.presentedViewController {
            return topVC(for: presentedController)
        }
        else {
            return rootViewController
        }
    }
}
